import type { Response } from '@/utils/types';
import type { WhereOptions } from 'sequelize/types';

import type { MenuManagementListDto } from './dto';

// cwind_international 实体
import { CwindMenus } from '@/models/cwind_menus.model'; // cwind_menu 实体
// cwind_user 实体
import { responseMessage } from '@/utils'; // 全局工具函数
/*
 * @Description: MenuManagement Service
 * @Version: 2.0
 * @Author: cwind
 * @Date: 2022-10-27 10:37:42
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-05-15 10:24:23
 */
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Sequelize } from 'sequelize-typescript';

import { initializeTree } from './help/handleMenu';

@Injectable()
export class MenusManagementService {
  constructor(
    // 使用 InjectModel 注入参数，注册数据库实体
    @InjectModel(CwindMenus)
    private readonly menuModel: typeof CwindMenus,
    private sequelize: Sequelize,
  ) {}

  async getMenuList(): Promise<Response<MenuManagementListDto[]>> {
    // 解构参数
    // const { menu_type, status, isPremission, start_time, end_time } = menuInfo;
    // 拼接查询参数
    const where: WhereOptions = {};
    // 查询数据
    const sqlData = await this.menuModel.findAll({
      attributes: [
        'menu_id',
        'name',
        'status',
        'type',
        'icon',
        'path',
        'component',
        'title',
        'affix_tab',
        'order',
        'pid',
        'permission',
        'badge',
        'badge_type',
        'badge_variants',
        'iframe_src',
        'link',
      ],
      raw: true,
      where,
      order: [
        ['order', 'desc'],
        ['created_time', 'desc'],
      ], // 排序规则,
    });
    // 将数据转成树形结构
    const routes = initializeTree(sqlData);
    return responseMessage(routes);
  }
}
